package com.mzm.domain;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

import com.mzm.PathUtils;

@Entity(name = "Category")
@Table(name = "CATEGORY")
public class Category extends BaseEntity {

	@Column(name = "NAME")
	private String name;

	@Column(name = "PATH")
	private String path;
	
	@ManyToOne
	@Cascade( { CascadeType.REFRESH })
	@JoinColumn(name = "PARENT_ID")
	private Category parent;

	@Transient
	private List<Category> children;

	public Category() {
		super();
	}

	public Category(String path, Category parent) {
		this.path = path;
		this.name = PathUtils.getLeafNodeName(path);
		this.parent = parent;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Category getParent() {
		return parent;
	}

	public void setParent(Category parent) {
		this.parent = parent;
	}

	public List<Category> getChildren() {
		return children;
	}

	public void setChildren(List<Category> children) {
		this.children = children;
	}
	
	public void addChild(Category child){
		if(this.children == null){
			this.children = new ArrayList<Category>();
		}
		this.children.add(child);
	}

	@PrePersist
	public void calcPath() {
		if (parent == null) {
			path = PathUtils.PATH_SEPERATOR;
			return;
		}
		String parentPath = parent.getPath();
		String sep = parentPath.endsWith(PathUtils.PATH_SEPERATOR) ? "" : PathUtils.PATH_SEPERATOR;
		this.path = parentPath + sep + getName();
	}
}
